# Create your views here.
from cep import Correios
import datetime
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import Http404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.template import Context, loader
from django.views.decorators.csrf import csrf_protect, requires_csrf_token
from stat import UF_APPEND

from elearning.escola.models import Disciplina, Endereco, Professor, Admin,\
    AlunoCursaDisciplina, Aluno, EnderecoAluno


@login_required
def index(request):   
    t = loader.get_template('elearning/index.html')
    #carrega o contexto com dados da lista
    if Admin.objects.filter(username=request.user).count() > 0: 
        c = Context({
            'admin':True,
            'professor_list': Professor.objects.all(),
            'alunos_list': Aluno.objects.all(),
            'usuario':request.user
        })
        return HttpResponse(t.render(c))
    if Professor.objects.filter(username=request.user).count() > 0: 
        prof = Professor.objects.get(username=request.user)
        dlist = []
        for d in Disciplina.objects.all():
            if(d.professor_id == prof.id):
                dlist.append(d)
        if len(dlist) == 0:
            dlist = None
        c = Context({
            'admin':False,
            'professor':True,
            'professor_list': None,
            'disciplina_list': dlist,
            'usuario':request.user
        })
        return HttpResponse(t.render(c))
    if Aluno.objects.filter(username=request.user).count() > 0: 
        aluno = Aluno.objects.get(username=request.user)
        dlist = []
        for d in AlunoCursaDisciplina.objects.all():
            if(aluno.pk == d.aluno_id):
                disciplina = Disciplina.objects.get(pk=d.disciplina_id)
                dlist.append(disciplina)
        if len(dlist) == 0:
            dlist = None
        c = Context({
            'admin':False,
            'professor':False,
            'aluno':True,
            'professor_list': None,
            'disciplina_list': dlist,
            'usuario':request.user
        })
        return HttpResponse(t.render(c))
    return render_to_response('elearning/index.html')

@login_required
def professor_detail(request, professor_id):
    try:
        p = Professor.objects.get(pk=professor_id)
        e = p.endereco_set.get(pk=p.id)
        dlist = []
        for d in Disciplina.objects.all():
            if(d.professor_id == p.id):
                dlist.append(d)
    except Professor.DoesNotExist:
        raise Http404
    if Admin.objects.filter(username=request.user).count() > 0: 
        return render_to_response('elearning/professor_detail.html', {'professor': p, 'endereco': e, 'admin':True, 'disciplina_list': dlist})
    return render_to_response('elearning/professor_detail.html', {'professor': p, 'endereco': e, 'disciplina_list': dlist})
        
    
    #return HttpResponse(t.render(c))

@login_required
def deletar(request, professor_id):
    p = get_object_or_404(Disciplina, pk=professor_id)
    p.delete()
    return index(request)
    
def user_login(request):
    return render_to_response('accounts/user_login.html')

def buscar_cep(request):
    return render_to_response('elearning/buscarCEP.html')

def buscar_cep_aluno(request):
    return render_to_response('elearning/buscarCEPaluno.html')

def verificar_login(request):
    print "verificando login..."
    u = request.POST['username']
    p = request.POST['password']    
    if Admin.objects.filter(username=u).count() > 0:
        adm = Admin.objects.get(username=u)
        print adm.password
        if adm.password == p and User.objects.filter(username=u).count() == 0:
            User.objects.create_user(u, adm.email, p)
    user = authenticate(username=u, password=p)
    if user is not None:
        login(request, user)
        print "login efetuado!"
        return index(request)
    else:
        return render_to_response('accounts/user_login.html')

def cadastrar(request):
    return render_to_response('accounts/cadastrar.html')

def efetuar_cadastro_admin(request):
    u = request.POST['username']
    e = request.POST['email']
    p = request.POST['password']
    c = request.POST['admin_code']
    if User.objects.filter(username=u).count() > 0:
        return render_to_response('accounts/cadastrar.html')
    if c.find('elearning_admin_2014') == 0:
        User.objects.create_user(u, e, p)
        a = Admin(username=u)
        a.save()     
        return HttpResponseRedirect(reverse('elearning.escola.views.index'))
    return render_to_response('accounts/cadastrar.html')

def validar_cep(request):
    try:
        cep = request.POST['cep']
        c = Correios()
        resultado = c.consulta(cep)
        if len(resultado) == 0:
            return render_to_response('elearning/buscarCEP.html', {'error':'CEP nao encontrado'})
        else:
            cidade = resultado[0]['Localidade']
            bairro = resultado[0]['Bairro']
            uf = resultado[0]['UF']
            rua = resultado[0]['Logradouro']
            return cadastrar_professor(request, cep, cidade, bairro, uf, rua)
    except ValueError:
        return render_to_response('elearning/buscarCEP.html', {'error':'CEP deve ser informado'})

def validar_cep_aluno(request):
    try:
        cep = request.POST['cep']
        c = Correios()
        resultado = c.consulta(cep)
        if len(resultado) == 0:
            return render_to_response('elearning/buscarCEP.html', {'error':'CEP nao encontrado'})
        else:
            cidade = resultado[0]['Localidade']
            bairro = resultado[0]['Bairro']
            uf = resultado[0]['UF']
            rua = resultado[0]['Logradouro']
            return cadastrar_aluno(request, cep, cidade, bairro, uf, rua)
    except ValueError:
        return render_to_response('elearning/buscarCEP.html', {'error':'CEP deve ser informado'})

@login_required
def cadastrar_professor(request, cep,cidade,bairro,uf,rua, erro=None):
    t = loader.get_template('elearning/criarProfessor.html')
    c = Context({
        'error':erro,
        'cep':cep,
        'cidade':cidade,
        'bairro':bairro,
        'uf': uf,
        'rua': rua        
    })
    return HttpResponse(t.render(c))

@login_required
def cadastrar_aluno(request, cep,cidade,bairro,uf,rua, erro=None):
    t = loader.get_template('elearning/criarAluno.html')
    c = Context({
        'error':erro,
        'cep':cep,
        'cidade':cidade,
        'bairro':bairro,
        'uf': uf,
        'rua': rua        
    })
    return HttpResponse(t.render(c))

@login_required
def efetuar_cadastro_aluno(request):
    u = request.POST['username']
    e = request.POST['email']
    p = request.POST['password']
    p2 = request.POST['password2']
    rue = request.POST['rua']
    num = request.POST['num']
    barrio = request.POST['bairro']
    city = request.POST['cidade']
    state = request.POST['estado']
    cepe = request.POST['cep']
    name = request.POST['nome']
    mat = request.POST['matricula']
    
    if User.objects.filter(username=u).count() > 0:
        return cadastrar_aluno(request, cepe, city, barrio, state, rue, erro='Username indisponivel')
    if p.find(p2) != 0:
        return cadastrar_aluno(request, cepe, city, barrio, state, rue, erro='Senhas nao coincidem')
    if Aluno.objects.filter(matricula=mat).count() > 0:
        return cadastrar_aluno(request, cepe, city, barrio, state, rue, erro='Matricula indisponivel')
    aluno = Aluno(username=u,nome=name,matricula=mat,email=e)
    aluno.save()
    aluno.enderecoaluno_set.create(rua=rue, numero=num, bairro=barrio,cidade=city,estado=state,cep=cepe)
    aluno.save()
    user = User.objects.create_user(u, e, p)
    user.save()
    return HttpResponseRedirect(reverse('elearning.escola.views.index'))

@login_required
def cadastrar_disciplina(request, professor_id, erro=None):
    return render_to_response('elearning/criarDisciplina.html', {'p_id':professor_id, 'error':erro})

@login_required
def efetuar_cadastro_professor(request):
    u = request.POST['username']
    e = request.POST['email']
    p = request.POST['password']
    p2 = request.POST['password2']
    rue = request.POST['rua']
    num = request.POST['num']
    barrio = request.POST['bairro']
    city = request.POST['cidade']
    state = request.POST['estado']
    cepe = request.POST['cep']
    name = request.POST['nome']
    pcfp = request.POST['cpf']
    tel = request.POST['telefone']
    
    if User.objects.filter(username=u).count() > 0:
        return cadastrar_professor(request, cepe, city, barrio, state, rue, erro='Username indisponivel')
    if p.find(p2) != 0:
        return cadastrar_professor(request, cepe, city, barrio, state, rue, erro='Senhas nao coincidem')
    prof = Professor(username=u, telefone=tel,nome=name,cpf=pcfp,email=e)
    prof.save()
    prof.endereco_set.create(rua=rue, numero=num, bairro=barrio,cidade=city,estado=state,cep=cepe)
    prof.save()
    user = User.objects.create_user(u, e, p)
    user.save()
    return HttpResponseRedirect(reverse('elearning.escola.views.index'))
    
@login_required
def efetuar_cadastro_disciplina(request, professor_id):
    prof = get_object_or_404(Professor, pk=professor_id)
    n = request.POST['nome']
    c = request.POST['conteudo']
    carga_horaria = request.POST['carga_horaria']
    if Disciplina.objects.filter(nome=n).count() > 0:
        return cadastrar_disciplina(request, professor_id, 'Disciplina ja cadastrada')
    prof.disciplina_set.create(nome=n,conteudo=c,cargaHoraria=carga_horaria)
    prof.save()
    return HttpResponseRedirect(reverse('elearning.escola.views.index'))

@login_required
def listarProfessores(request):
    t = loader.get_template('elearning/listarProfessores.html') 
    c = Context({
        'professor_list': Professor.objects.all()
    })
    return HttpResponse(t.render(c))

@login_required
def listarDisciplinas(request):
    t = loader.get_template('elearning/listarDisciplinas.html') 
    c = Context({
        'disciplinas_list': Disciplina.objects.all(),
    })
    return HttpResponse(t.render(c))

def user_logout(request):
    logout(request)
    return HttpResponseRedirect(reverse('elearning.escola.views.index'))

def listarAlunosDaDisciplina(request, disciplina_id):
    disciplina = Disciplina.objects.get(pk=disciplina_id)
    dis = disciplina.nome
    professor = Professor.objects.get(pk=disciplina.professor_id)
    alunos = []
    for aluDis in AlunoCursaDisciplina.objects.all():
        if(disciplina.pk == aluDis.disciplina_id):
            aluno = Aluno.objects.get(pk=aluDis.aluno_id)
            alunos.append(aluno)    
    t = loader.get_template('elearning/listarAlunosDaDisciplina.html') 
    c = Context({
        'disciplina':disciplina,
        'alunos_list':alunos,
        'professor': professor
    })
    if Aluno.objects.filter(username=request.user).count() > 0:
        al = Aluno.objects.get(username=request.user)
        c = Context({
            'disciplina':disciplina,
            'alunos_list':alunos,
            'professor': professor,
            'aluno':al
        })    
    return HttpResponse(t.render(c))

@login_required
def aluno_detail(request, aluno_id):
    try:
        a = Aluno.objects.get(pk=aluno_id)
        e = a.enderecoaluno_set.get(professor=aluno_id)
        dlist = []
        for d in AlunoCursaDisciplina.objects.all():
            if a.pk == d.aluno_id:
                disciplina = Disciplina.objects.get(pk=d.disciplina_id)
                dlist.append(disciplina)
    except Aluno.DoesNotExist:
        raise Http404
    return render_to_response('elearning/aluno_detail.html', {'aluno': a, 'endereco': e, 'disciplina_list': dlist})

def cadastrarNaDisciplina(request, aluno_id, disciplina_id):
    a = Aluno.objects.get(pk=aluno_id)
    dis = Disciplina.objects.get(pk=disciplina_id)
    for d in AlunoCursaDisciplina.objects.all():
        if d.disciplina_id == dis.pk and d.aluno_id == a.pk:
            return HttpResponseRedirect(reverse('elearning.escola.views.index'))
    acd = AlunoCursaDisciplina(disciplina=dis, aluno=a, nota=0, faltas=0)
    acd.save()
    return HttpResponseRedirect(reverse('elearning.escola.views.index'))